package com.xgh.sortMethods;

/**
 * @ClassName BinarySearch
 * @Description
 * @Author xinggh
 * @Date 2020/8/17 0:44
 * @Version 1.0
 **/
public class BinarySearch {


    public static int first(int arr[], int target) {

        int left = 0;
        int right = arr.length - 1;

        while (left < right) {
            int mid = (left + right) / 2;
            if (arr[mid] < target) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return left + 1;
    }

    public static int last(int arr[], int target) {

        int left = 0;
        int right = arr.length - 1;

        while (left < right) {
            int mid = (left + right) / 2;
            if (arr[mid] > target) {
                right = mid - 1;
            } else {
                left = mid;
            }
        }
        return right;
    }

    public static void main(String[] args) {
        int arr[] = new int[]{0, 1, 2, 2, 2, 3, 4, 5};
        System.out.println(last(arr, 2));
    }
}
